#include   "Buzzer.h"

static void GPIO_config(void) {
	GPIO_InitTypeDef	GPIO_InitStructure;		//结构定义
    // 蜂鸣器  准双向口
	GPIO_InitStructure.Pin  = GPIO_Pin_4;		//指定要初始化的IO,
	GPIO_InitStructure.Mode = GPIO_PullUp;	//指定IO的输入或输出方式,GPIO_PullUp,GPIO_HighZ,GPIO_OUT_OD,GPIO_OUT_PP
	GPIO_Inilize(GPIO_P3, &GPIO_InitStructure);//初始化
	BUZZER = 0; // 拉低
}

static void	PWM_config(u16 hz_value) // 为0，停止播放
{
	PWMx_InitDefine		PWMx_InitStructure;
	u16  period = 0; // 周期变量
	if (hz_value != 0)  period =  (MAIN_Fosc / hz_value); 
	// 配置PWM8
	PWMx_InitStructure.PWM_Mode    		= CCMRn_PWM_MODE1;	//模式,		CCMRn_FREEZE,CCMRn_MATCH_VALID,CCMRn_MATCH_INVALID,CCMRn_ROLLOVER,CCMRn_FORCE_INVALID,CCMRn_FORCE_VALID,CCMRn_PWM_MODE1,CCMRn_PWM_MODE2
	PWMx_InitStructure.PWM_Duty    		= 0.5 * period;	//PWM占空比时间, 0~Period
	// 不为0，正常配置通道，为0，不配置通道
	PWMx_InitStructure.PWM_EnoSelect    = hz_value == 0 ? 0 : ENO8P;			//输出通道选择,	ENO1P,ENO1N,ENO2P,ENO2N,ENO3P,ENO3N,ENO4P,ENO4N / ENO5P,ENO6P,ENO7P,ENO8P
	PWM_Configuration(PWM8, &PWMx_InitStructure);			//初始化PWM,  PWMA,PWMB

	// 配置PWMB
	PWMx_InitStructure.PWM_Period   = period - 1;			//周期时间,   0~65535
	PWMx_InitStructure.PWM_DeadTime = 0;					//死区发生器设置, 0~255
	PWMx_InitStructure.PWM_MainOutEnable= ENABLE;			//主输出使能, ENABLE,DISABLE
	PWMx_InitStructure.PWM_CEN_Enable   = ENABLE;			//使能计数器, ENABLE,DISABLE
	PWM_Configuration(PWMB, &PWMx_InitStructure);			//初始化PWM通用寄存器,  PWMA,PWMB
	// 切换PWM通道
	PWM8_SW(PWM8_SW_P34);	

	// 初始化PWMB的中断
	NVIC_PWM_Init(PWMB,DISABLE,Priority_0);
}

void Buzzer_init() {
    EAXSFR();		/* 扩展寄存器访问使能 */
    GPIO_config();
}

void Buzzer_play(u16 hz_value) {
    PWM_config(hz_value);
}
//			        
u16 code FREQS[] = {
	523 * 1, 587 * 1, 659 * 1, 698 * 1, 784 * 1, 880 * 1, 988 * 1, 
	523 * 2, 587 * 2, 659 * 2, 698 * 2, 784 * 2, 880 * 2, 988 * 2, 
	523 * 4, 587 * 4, 659 * 4, 698 * 4, 784 * 4, 880 * 4, 988 * 4, 
	523 * 8, 587 * 8, 659 * 8, 698 * 8, 784 * 8, 880 * 8, 988 * 8, 
};

// 根据索引取出对应的音调  
void Buzzer_beep(u8 idx) {
    PWM_config(FREQS[idx]);
}

void Buzzer_alarm() {
	Buzzer_beep(9);
	os_wait2(K_TMO, 20);  // 5ms * 20
	Buzzer_stop();
	os_wait2(K_TMO, 10);  // 5ms * 10
	
	Buzzer_beep(8);
	os_wait2(K_TMO, 20);  // 5ms * 20
	Buzzer_stop();
	os_wait2(K_TMO, 10);  // 5ms * 10
	
	Buzzer_beep(7);
	os_wait2(K_TMO, 20);  // 5ms * 20
	Buzzer_stop();
	os_wait2(K_TMO, 10);  // 5ms * 10
}

void Buzzer_stop() {
    PWM_config(0);
	
	BUZZER = 0; // 拉低
}